package bma.common.langutil.jmshell;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import bma.common.langutil.core.ExceptionUtil;
import bma.common.langutil.core.ValueUtil;
import bma.common.langutil.jmshell.cmdopt.CommandOptionParser;
import bma.common.langutil.jmshell.command.CommandProcessor;
import bma.common.langutil.jmshell.command.CommandSet;

public class JMShellUtil {

	public static boolean isCommand(String text, String cmd) {
		if (text == null)
			return false;
		if (ValueUtil.empty(cmd))
			return false;
		String str = text.trim();
		if (cmd.equals(str))
			return true;
		if (str.startsWith(cmd + " "))
			return true;
		return false;
	}

	public static boolean isCommand(String text, String[] cmds) {
		if (cmds == null)
			return false;
		for (String c : cmds) {
			if (isCommand(text, c))
				return true;
		}
		return false;
	}

	public static final String SESSION_KEY_REMOTE_IP = "remoteIp";

	public static String getRemoteIp(Session s) {
		Object r = s.getAttribute(SESSION_KEY_REMOTE_IP);
		return r == null ? null : r.toString();
	}

	public static boolean listCommand(Session session, CommandSet cset,
			CommandOptionParser options, List<String> preset) {
		List<String> cmds = new ArrayList<String>();
		if (preset != null) {
			cmds.addAll(preset);
		}
		if (cset != null) {
			cset.listCommands(session, cmds);
		}
		Set<String> clist = new TreeSet<String>(cmds);

		StringBuilder sb = new StringBuilder();
		sb.append("commands: ");
		Iterator<String> it = clist.iterator();
		while (it.hasNext()) {
			String cmd = it.next();
			sb.append(cmd);
			if (it.hasNext())
				sb.append(", ");
		}
		session.writeln(sb.toString());
		return true;
	}

	public static void handleListCommand(Session session, List<String> results,
			JMShellProcessor p) {
		if (p == null) {
			return;
		}
		if (p instanceof CommandSet) {
			CommandSet cset = (CommandSet) p;
			cset.listCommands(session, results);
			return;
		}
		if (p instanceof CommandProcessor) {
			CommandProcessor cmd = (CommandProcessor) p;
			results.add(cmd.getCommand());
			return;
		}
	}

	public static <TYPE> TYPE getData(Session s, String name, Class<TYPE> cls,
			boolean sure) {
		Object o = s.getAttribute(name);
		if (o == null && sure) {
			try {
				o = cls.newInstance();
				s.setAttribute(name, o);
			} catch (Exception e) {
				throw ExceptionUtil.throwRuntime(e);
			}
		}
		return o == null ? null : cls.cast(o);
	}

	public static boolean checkAccept(Session s, String op) {
		return true;
	}
}
